package cn.shop.dys.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.shop.dys.R;
import cn.shop.dys.activity.ProductListShowActivity;
import cn.shop.dys.adapter.CategoryAdapter;
import cn.shop.dys.adapter.CategoryCommonViewHolder;
import cn.shop.dys.adapter.CategorySecondAdapter;
import cn.shop.dys.adapter.CommonListAdapter;
import cn.shop.dys.bean.CategoryInfo;
import cn.shop.dys.bean.CategoryItem;
import cn.shop.dys.bean.CategoryJson;
import cn.shop.dys.bean.CategoryType;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.Constant;
import cn.shop.dys.util.CategoryViewPager;


/**
 * 分类
 */
public class CategoryFragment extends BaseFragment {

    private ArrayList<CategoryType> list;
    private GridView listView;
    private CategoryAdapter categoryAdapter;
    private CategoryType type;
    private ProgressBar progressBar;
    private String typename;
    private List<CategoryItem> items;
    private ListView recycler;
    public int[] datas;
private  int preIndex=0;

    private static final int RESULT_OK = 10;
    private static final int RESULT_CANCELED = 30;
    //private View view;
    private HttpUtils httpUtils;
    private Gson gson;
    private List<CategoryInfo> categoryInfos;
    private List<CategoryInfo> first;
    private Map<String, List<CategoryInfo>> map;
    private Map<String, List<CategoryInfo>> thirdMap;
    private BitmapUtils bitmapUtils;


    private View view;
    private View head;
    private CategoryInfo listInfo;
    public String toolsList[];
    public TextView toolsTextViews[];
    private View views[];
    private ViewPager shop_pager;
    private ListView listViewFirst;
    private CategorySecondAdapter categorySecondAdapter;
    private TextView second_tv;
    private ImageView second_iv;
    private CommonListAdapter<CategoryInfo> listAdapter;
    private ArrayList<String> strings;


    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        view = inflater.inflate(R.layout.category_fragment_pro_type_copy, null);
        listView = (GridView) view.findViewById(R.id.listView);
        strings = new ArrayList<>();
        strings.add("125");
        strings.add("142");
        strings.add("111");
        strings.add("136");
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, ProductListShowActivity.class);
                intent.putExtra(Constant.KEY_ID,strings.get(position%4));
                startActivity(intent);
            }
        });
        bitmapUtils = new BitmapUtils(getActivity());
        //json传送数据
        jsonSecond();
        initFirst();
      //  initSecond();

        //轮播图
        initDatas();
        CategoryViewPager mvp = (CategoryViewPager) view.findViewById(R.id.first_carouse);
        mvp.setItems(items);




        return view;


    }




    private void initFirst() {

        RequestCallBack<String> callback = new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                CategoryJson categoryJson = gson.fromJson(result, CategoryJson.class);
                // TODO: 2016/4/19
//                MyLogger.jLog().i(result);
                sortData(categoryJson);
                setFirstAdapter();
                //setSecondAdapter();

//                List<CategoryInfo> categoryInfos = new ArrayList<>();

                listAdapter = new CommonListAdapter<CategoryInfo>(first.get(0), mContext, R.layout.category_gridview_item) {
                    @Override
                    protected void bindData(CategoryCommonViewHolder holder, List<CategoryInfo> list, int position) {
                        try {
                            CategoryInfo info = list.get(position);
                            Log.i("info",""+first);
//                            List<CategoryInfo> list_id = map.get(info.id);
                            Glide
                                    .with(mContext)
                                    .load(Constant.getUrl(CommonConstant.HOST+info.pic))
                                    .centerCrop()
                                    .placeholder(R.drawable.goods_one)
                                    .crossFade()
                                    .into(holder.getImageView(R.id.gridview_iv));
                            holder.getTextView(R.id.gridview_tv).setText(info.name);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                listView.setAdapter(listAdapter);

            }

            @Override
            public void onFailure(HttpException e, String s) {


            }
        };

        httpUtils.send(HttpRequest.HttpMethod.GET, Constant.url, callback);

    }


    ///json解析
    private void jsonSecond() {

        listInfo = new CategoryInfo();

        gson = new Gson();
        httpUtils = new HttpUtils();

        //listViewFirst = (ListView) root.findViewById(R.id.lv_first);
        RequestCallBack<String> callback = new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                CategoryJson categoryJson = gson.fromJson(result, CategoryJson.class);
                // TODO: 2016/4/19
                // CommonUtil.showSingleToast(mContext,result);
                //Log.d("chenyi","成功");
                sortData(categoryJson);


            }

            @Override
            public void onFailure(HttpException e, String s) {

//                CommonUtil.showSingleToast(CategoryFragment.this,result);

              // Log.d("chenyi","失败");
            }
        };

        httpUtils.send(HttpRequest.HttpMethod.GET, Constant.url, callback);


    }



    //轮播图textview
    private void initDatas() {
        items = new ArrayList<CategoryItem>();

        items.add(new CategoryItem("url1", "大放送，为回馈客户今日买一送十"));
        items.add(new CategoryItem("url2", "今日商城所有东西，全部半价"));
        items.add(new CategoryItem("url3", "以上全部，都是玩笑"));
    }


    //list的适配，从服务器获得数据
    private void setFirstAdapter() {
        listViewFirst = (ListView) view.findViewById(R.id.sctoltools_tools);

        categoryAdapter = new CategoryAdapter(mContext, R.layout.category_first_item, R.id.tv, first);
        listViewFirst.setAdapter(categoryAdapter);
        firstListViewOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CategoryInfo info = first.get(position);
//                List<CategoryInfo> list = map.get(info.id);
                preIndex=position;
                // TODO: 2016/4/20
                if (categoryAdapter.preDisableIndex != position) {
                    view.setEnabled(false);
                    parent.getChildAt(categoryAdapter.preDisableIndex).setEnabled(true);
                    categoryAdapter.preDisableIndex = position;
                }
                listAdapter.addItem(info);



//                Log.i("chenyi",list.toString());
//                categorySecondAdapter.setList(list);


               // Glide.with(mContext).load("Constant.getUrl(info.pic)").into(second_iv);
//                Glide
//                        .with(mContext)
//                        .load(Constant.getUrl(info.pic))
//                        .centerCrop()
//                        .placeholder(R.drawable.goods_one)
//                        .crossFade()
//                        .into(second_iv);

                //有圆角的图片加载
//                Glide.with(context).load(urls.get(i).getUrl()).fitCenter().into(imageViewHolder.image);
//                imageViewHolder.image.setTag(R.id.image_tag, i);
//                imageViewHolder.image.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    int position = (int) v.getTag(R.id.image_tag);
//                    Toast.makeText(context, urls.get(position).getWho(), Toast.LENGTH_SHORT).show();
//                }
//            });

                //bitmapUtils.display(second_iv, Constant.getUrl(info.pic));
                //waterFall_tv.setText(info.name);
//                second_tv.setText(info.name);
            }
        };
        listViewFirst.setOnItemClickListener(firstListViewOnItemClickListener);
        listViewFirst.setSelection(0);
    }


    private AdapterView.OnItemClickListener firstListViewOnItemClickListener;



//    private void setSecondAdapter() {
//        categorySecondAdapter = new CategorySecondAdapter(map.get(map.keySet().iterator().next()), bitmapUtils, first.get(0), second_iv, second_tv, thirdMap);
//
//        recycler.setAdapter(categorySecondAdapter);
//    }





    //CategoryJson的传递和便利
    public void sortData(CategoryJson categoryJson) {
        categoryInfos = categoryJson.category;
        first = new ArrayList<>();
        for (CategoryInfo categoryInfo : categoryInfos) {
            if ("0".equals(categoryInfo.parentId)) {
                first.add(categoryInfo);
            }
        }
        categoryInfos.removeAll(first);

        map = new HashMap<>();
        List<CategoryInfo> thirdList = new ArrayList<>();
        Set<String> secondIds = new HashSet<>();
        for (CategoryInfo categoryInfo : categoryInfos) {
            if (categoryInfo.isLeafNode.equals("true")) {
                thirdList.add(categoryInfo);
                secondIds.add(categoryInfo.parentId);
            }
        }
        categoryInfos.removeAll(thirdList);
        thirdMap = new HashMap<>();
        for (CategoryInfo categoryInfo : first) {
            List<CategoryInfo> second = new ArrayList<>();
            for (CategoryInfo info : categoryInfos) {
                if (info.parentId.equals(categoryInfo.id)) {
                    second.add(info);
                }
            }
            map.put(categoryInfo.id, second);
        }
        for (CategoryInfo categoryInfo : categoryInfos) {
            List<CategoryInfo> infos = new ArrayList<>();
            for (CategoryInfo info : thirdList) {

                if (info.parentId.equals(categoryInfo.id)) {
                    infos.add(info);
                }
            }
            thirdMap.put(categoryInfo.id, infos);
        }

        //Log.d("chenyi",thirdMap.toString());
    }

}

